import signal
import sys
from concurrent import futures
import grpc
from loguru import logger

from config import BASE_DIR
from user.handlers.user import UserService
from user.proto import user_pb2_grpc

sys.path.insert(0, BASE_DIR)


class LogInterceptor(grpc.ServerInterceptor):
    def intercept_service(self, continuation, handler_call_details):
        print('start...')
        print(type(handler_call_details))
        rsp = continuation(handler_call_details)
        print('end...')
        return rsp


def on_exit(signo, frame):
    logger.info(f'signal terminal, signal num: {signo}, frame: {frame}')
    sys.exit(0)


def init():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10), interceptors=(LogInterceptor(),))
    user_pb2_grpc.add_UserServiceServicer_to_server(UserService(), server)
    server.add_insecure_port("0.0.0.0:10059")
    logger.info('server start, listen 10059...')

    signal.signal(signal.SIGINT, on_exit)
    signal.signal(signal.SIGTERM, on_exit)

    server.start()
    # 等待结束
    server.wait_for_termination()


if __name__ == '__main__':
    init()
